package middleware

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

const (
	cacheControlHeader = "Cache-Control"
	cacheControlValue  = "public, max-age=604800" // 缓存一周
	eTagHeader         = "ETag"
	ifNoneMatchHeader  = "If-None-Match"
	lastModifiedHeader = "Last-Modified"
)

// CacheMiddleware 是一个中间件，用于设置缓存控制头和 ETag
func CacheMiddleware(c *gin.Context) {
	key := c.Param("key")
	eTag := key

	// 设置缓存头
	c.Header(cacheControlHeader, cacheControlValue)
	c.Header(eTagHeader, eTag)

	// 检查 If-None-Match 头与生成的 ETag 是否匹配
	if match := c.GetHeader(ifNoneMatchHeader); match != "" {
		if match == eTag {
			log.Printf("Cache hit for image key: %s", key)
			c.Status(http.StatusNotModified)
			c.Abort()
			return
		}
	}
}
